import autoDisposeWhenUnload from "./autoDisposeWhenUnload";
import {UNDEFINED} from "./others";

const instanceList = [];
const dataList = [];

autoDisposeWhenUnload(function () {
    instanceList.forEach(i => i?.destroy());
    instanceList.splice(0, instanceList.length);
    dataList.splice(0, dataList.length);
});

export default class InfiniteLoopGet {
    constructor(list) {
        instanceList.push(this);
        dataList.push({
            list: list || [],
            index: -1,
        });
    }

    get() {
        const data = dataList[instanceList.indexOf(this)];
        if (0 === data.list.length) {
            return UNDEFINED;
        } else if (1 === data.list.length) {
            return data.list[0];
        } else if (1 + data.index < data.list.length) {
            data.index++;
        } else {
            data.index = 0;
        }
        return data.list[data.index];
    }

    destroy() {
        const index = instanceList.indexOf(this);
        instanceList[index] = null;
        dataList[index] = null;
    }
}
